package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDomain;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDomainService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * 问题领域Controller
 * 
 * @author ruoyi
 * @date 2022-05-07
 */
@RestController
@RequestMapping("/system/domain")
public class SysDomainController extends BaseController
{


    @Autowired
    private ISysDomainService domainService;

    /**
     * 获取领域列表
     */
    //@PreAuthorize("@ss.hasPermi('system:domain:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDomain domain)
    {
        List<SysDomain> domains = domainService.selectDomainList(domain);
        return AjaxResult.success(domains);
    }

    /**
     * 查询领域列表（排除节点）
     */
    //@PreAuthorize("@ss.hasPermi('system:domain:list')")
    @GetMapping("/list/exclude/{domainId}")
    public AjaxResult excludeChild(@PathVariable(value = "domainId", required = false) Long domainId)
    {
        List<SysDomain> domains = domainService.selectDomainList(new SysDomain());
        Iterator<SysDomain> it = domains.iterator();
        while (it.hasNext())
        {
            SysDomain d = (SysDomain) it.next();
            if (d.getDomainId().intValue() == domainId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), domainId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(domains);
    }

    /**
     * 根据领域编号获取详细信息
     */
   // @PreAuthorize("@ss.hasPermi('system:domain:query')")
    @GetMapping(value = "/{domainId}")
    public AjaxResult getInfo(@PathVariable Long domainId)
    {
        domainService.checkDomainDataScope(domainId);
        return AjaxResult.success(domainService.selectDomainById(domainId));
    }



    /**
     * 获取领域下拉树列表
     */
  @GetMapping("/treeselect/{domainId}")
    public AjaxResult treeselect(@PathVariable Long domainId)
    {
        SysDomain domain=new SysDomain();
        domain.setDomainId(domainId);
        List<SysDomain> domains = domainService.selectDomainList(domain);
        return AjaxResult.success(domainService.buildDomainTreeSelect(domains));
    }

    /**
     * 获取领域下拉树列表
     */
   @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDomain domain)
    {
        List<SysDomain> domains = domainService.selectDomainList(domain);
        return AjaxResult.success(domainService.buildDomainTreeSelect(domains));
    }

    /**
     * 加载对应角色领域列表树
     */
    @GetMapping(value = "/roleDomainTreeselect/{roleId}")
    public AjaxResult roleDomainTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDomain> domains = domainService.selectDomainList(new SysDomain());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("domains", domainService.buildDomainTreeSelect(domains));
        return ajax;
    }

    /**
     * 新增领域
     */
   // @PreAuthorize("@ss.hasPermi('system:domain:add')")
    @Log(title = "领域管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDomain domain)
    {
        if (UserConstants.NOT_UNIQUE.equals(domainService.checkDomainNameUnique(domain)))
        {
            return AjaxResult.error("新增领域'" + domain.getDomainName() + "'失败，领域名称已存在");
        }
        domain.setCreateBy(getUsername());
        return toAjax(domainService.insertDomain(domain));
    }

    /**
     * 新增领域
     */
   // @PreAuthorize("@ss.hasPermi('system:domain:add')")
    @Log(title = "领域管理", businessType = BusinessType.INSERT)
    @PostMapping("/addRootDomain")
    public AjaxResult addRootDomain(@Validated @RequestBody SysDomain domain)
    {
        domain.setCreateBy(getUsername());
        return toAjax(domainService.inserRootDomain(domain));
    }




    /**
     * 修改领域
     */
 //   @PreAuthorize("@ss.hasPermi('system:domain:edit')")
    @Log(title = "领域管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDomain domain)
    {
        Long domainId = domain.getDomainId();
        domainService.checkDomainDataScope(domainId);
        if (UserConstants.NOT_UNIQUE.equals(domainService.checkDomainNameUnique(domain)))
        {
            return AjaxResult.error("修改领域'" + domain.getDomainName() + "'失败，领域名称已存在");
        }
        else if (domain.getParentId().equals(domainId))
        {
            return AjaxResult.error("修改领域'" + domain.getDomainName() + "'失败，上级领域不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, domain.getStatus()) && domainService.selectNormalChildrenDomainById(domainId) > 0)
        {
            return AjaxResult.error("该领域包含未停用的子领域！");
        }
        domain.setUpdateBy(getUsername());
        return toAjax(domainService.updateDomain(domain));
    }

    /**
     * 删除领域
     */
   // @PreAuthorize("@ss.hasPermi('system:domain:remove')")
    @Log(title = "领域管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{domainId}")
    public AjaxResult remove(@PathVariable Long domainId)
    {
        if (domainService.hasChildByDomainById(domainId))
        {
            return AjaxResult.error("存在下级领域,不允许删除");
        }
        if (domainService.checkDomainExist(domainId))
        {
            return AjaxResult.error("领域存在用户,不允许删除");
        }
        domainService.checkDomainDataScope(domainId);
        return toAjax(domainService.deleteDomainById(domainId));
    }
}
